package com.phkg.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.phkg.entity.Result;
import com.phkg.entity.User;
import com.phkg.mapper.LogMapper;
import com.phkg.mapper.UserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.text.SimpleDateFormat;
import java.util.Date;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserMapper userMapper;

    @Autowired
    LogMapper logMapper;


    @PostMapping("/register")
    public Result Register(User user) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, user.getUsername());
        if (userMapper.selectOne(queryWrapper) == null) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateFormat = simpleDateFormat.format(date);
            user.setCreateTime(dateFormat);
            return Result.success(userMapper.insert(user));
        }
        return Result.fail("账号已存在！");
    }

    @GetMapping("/login")
    public Result Login(String username, String password) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(User::getUsername, username).eq(User::getPassword, password);
        User user = userMapper.selectOne(queryWrapper);
        if (user != null) {
            Date date = new Date();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateFormat = simpleDateFormat.format(date);
            user.setLastLogin(dateFormat);
            userMapper.updateById(user);
            return Result.success("登录成功");
        }
        return Result.fail("账号或密码错误");
    }
}
